<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Blockly Demo: Rita - Generating Java</title>
    <script src="../blockly/blockly_compressed.js"></script>
    <script src="../blockly/blocks_compressed.js"></script>
    <script src="../blockly/java_compressed.js"></script>
    <script src="msg/js/en.js"></script>

    <script src="custom-blocks.js"></script>

    <style>
        body {
            background-color: #fff;
            font-family: sans-serif;
        }
        
        h1 {
            font-weight: normal;
            font-size: 140%;
        }
    </style>
</head>

<body>
    <h1>Rita2.0, con Blockly!</h1>

    <p>Probando los bloques para robocode :)</p>
    <div id="blocklyDiv" style="height: 480px; width: 600px;"></div>

    <div style="text-align:center;">
        <input type="text" placeholder="Please select a file" id="actual-file" disabled="disabled" />
        <input type="button" value="Choose a file" id="select-file" />
        <input type="button" id="save-changes" value="Save changes" />
    </div>
    <div id="codeDiv" style="height: 480px; width: 600px; margin: 10px 0">
        <button onclick="showCode()" style=" margin: 10px 0">Generar código Java</button>
        <input type="button" value="Create New File" id="create-new-file" />
        <br><br>
        <textarea name="resultCode" readonly="readonly" id="resultCode" cols="90" rows="50"></textarea>
    </div>

    <xml xmlns="http://www.w3.org/1999/xhtml" id="toolbox" style="display: none;">
        <category name="A Codificar" colour="#a55b5b">
            <block type="fn_run"></block>
            <block type="fn_onhitrobot"></block>
        </category>
        <category name="Movimiento" colour="#a56d5b">
            <block type="fn_ahead"></block>
            <block type="fn_back"></block>
        </category>
        <category name="Acciones" colour="#a55b6d">
            <block type="fn_fire"></block>
            <block type="fn_turngunright"></block>
            <block type="fn_turngunleft"></block>
        </category>
        <category name="Colors" colour="#a5935b">
            <block type="fn_setcolors"></block>
            <block type="colour_picker">
                <field name="COLOUR">#ff6600</field>
            </block>
            <block type="colour_picker">
                <field name="COLOUR">#ff0000</field>
            </block>
            <block type="colour_picker">
                <field name="COLOUR">#3333ff</field>
            </block>
            <block type="colour_picker">
                <field name="COLOUR">#ffffff</field>
            </block>
        </category>
        <category name="Lógica" colour="#5ba55b">
            <block type="controls_whileUntil">
                <field name="MODE">WHILE</field>
            </block>
            <block type="controls_if"></block>
        </category>
        <category name="Matemática" colour="#5b80a5">
            <block type="math_number">
                <field name="NUM">0</field>
            </block>
        </category>
    </xml>

    <xml xmlns="http://www.w3.org/1999/xhtml" id="startBlocks" style="display:none">
        <block type="fn_run" id="z}S%An_MLFM!`aVm[=:%" x="50" y="50" movable="false">
            <statement name="run">
                <block type="fn_setcolors" id="Cfxn*MhWGPA{4=$DqZ54">
                    <value name="bodyColor">
                        <block type="colour_picker" id="!+puTde0`U:[`%2G(WgT">
                            <field name="COLOUR">#ff0000</field>
                        </block>
                    </value>
                    <value name="gunColor">
                        <block type="colour_picker" id="9]NLUuf^UXr6iA4NhRu2">
                            <field name="COLOUR">#ff6600</field>
                        </block>
                    </value>
                    <value name="radarColor">
                        <block type="colour_picker" id="KGZ~AT5p-E4Q}HmlsRSV">
                            <field name="COLOUR">#3333ff</field>
                        </block>
                    </value>
                </block>
            </statement>
        </block>
    </xml>

    <script>
        var fs = require('fs');
        const {
            dialog
        } = require('electron').remote;

        document.getElementById('select-file').addEventListener('click', function() {
            dialog.showOpenDialog(function(fileNames) {
                if (fileNames === undefined) {
                    console.log("No file selected");
                } else {
                    document.getElementById("actual-file").value = fileNames[0];
                    readFile(fileNames[0]);
                }
            });
        }, false);

        document.getElementById('save-changes').addEventListener('click', function() {
            var actualFilePath = document.getElementById("actual-file").value;

            if (actualFilePath) {
                saveChanges(actualFilePath, document.getElementById('resultCode').value);
            } else {
                alert("Please select a file first");
            }
        }, false);

        document.getElementById('create-new-file').addEventListener('click', function() {
            var content = document.getElementById("resultCode").value;

            dialog.showSaveDialog(function(fileName) {
                if (fileName === undefined) {
                    console.log("You didn't save the file");
                    return;
                }

                fs.writeFile(fileName, content, function(err) {
                    if (err) {
                        alert("An error ocurred creating the file " + err.message)
                    }

                    alert("The file has been succesfully saved");
                });
            });
        }, false);

        function readFile(filepath) {
            fs.readFile(filepath, 'utf-8', function(err, data) {
                if (err) {
                    alert("An error ocurred reading the file :" + err.message);
                    return;
                }

                document.getElementById("resultCode").value = data;
            });
        }

        function saveChanges(filepath, content) {
            fs.writeFile(filepath, content, function(err) {
                if (err) {
                    alert("An error ocurred updating the file" + err.message);
                    console.log(err);
                    return;
                }

                alert("The file has been succesfully saved");
            });
        }

        var demoWorkspace = Blockly.inject('blocklyDiv', {
            media: 'media/',
            toolbox: document.getElementById('toolbox')
        });
        Blockly.Xml.domToWorkspace(document.getElementById('startBlocks'),
            demoWorkspace);

        function showCode() {
            // Generate Java code and display it.
            Blockly.Java.INFINITE_LOOP_TRAP = null;
            var code = Blockly.Java.workspaceToCode(demoWorkspace);
            // alert(code);
            document.getElementById("resultCode").value = code;
        }

        function runCode() {
            // Generate Java code and run it.
            window.LoopTrap = 1000;
            Blockly.Java.INFINITE_LOOP_TRAP =
                'if (--window.LoopTrap == 0) throw "Infinite loop.";\n';
            var code = Blockly.Java.workspaceToCode(demoWorkspace);
            Blockly.Java.INFINITE_LOOP_TRAP = null;
            try {
                eval(code);
            } catch (e) {
                alert(e);
            }
        }
    </script>

</body>

</html>
